package com.java.learn;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

@SuppressWarnings("unused")
public class CreatenewFile {
	//testing the without main method
	static{		
		//System.out.println("hello");
		//System.exit(0);
	}

	/**
	 * @param args
	 * @throws IOException 
	 */
	public static void main(String[] args) throws IOException {
		
		// TODO Auto-generated method stub
		//creating and writing to file
		String str = "ajay kumar Yadav";
		//System.out.println(str);
		File fl = new File("D:\\ajay.csv");
		if(!fl.exists()){			
			fl.createNewFile();
		}else{}
		//create class object to call methods
		CreatenewFile cnf = new CreatenewFile();
		cnf.writeCsvFile(fl,str);
		cnf.readCsvFile(fl);
			
	}
	//read csv files
	private void readCsvFile(File fl) throws FileNotFoundException {
		// TODO Auto-generated method stub
		
		//reading from files
		        FileReader fr = new FileReader(fl);
				BufferedReader br = new BufferedReader(fr);
				try {
					String output;
					while((output=br.readLine())!=null){
						System.out.println(output);						
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					try {
						br.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
	}

	private void writeCsvFile(File fl, String str) throws IOException {
		// TODO Auto-generated method stub
		FileWriter fw = new FileWriter(fl,true);
		BufferedWriter bw = new BufferedWriter(fw);
		bw.write(str);
		System.out.println("File successfully written");
		bw.close();		
	}

}
